package com.wheesper.www.WheesperServer.Net.Base;

import com.google.protobuf.InvalidProtocolBufferException;
import com.wheesper.www.WheesperServer.Common.Request;
import com.wheesper.www.WheesperServer.Common.TaskQueue;
import com.wheesper.www.WheesperServer.Net.Session.*;
import com.wheesper.www.WheesperServer.Utils.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import ProtocolBuffer.ProtoMessageOuterClass.ProtoMessage;
import ProtocolBuffer.ProtoMessageOuterClass.SignoutRequest;

public class SessionChannelHandler extends ChannelInboundHandlerAdapter {
	private IOSession _session;
	private SessionManager _session_manager;
	private TaskQueue<Request> _taskqueue;
	private int _protoMessageLength = 0;
	
	public SessionChannelHandler(TaskQueue<Request> _taskqueue,SessionManager manager) {
		this._taskqueue = _taskqueue;
		_session_manager = manager;
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		System.out.print("[New Client Connected to Server]");
		_session = _session_manager.newIOSession(ctx.channel());
		System.out.println("{\nSession:" + _session.getID()+"\n}");
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx,Throwable cause) {
		cause.printStackTrace();
		ctx.close();
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx,Object msg) {
		ByteBuf in = (ByteBuf)msg;
		
		if(_protoMessageLength == 0 && in.readableBytes() >= 4) {
			_protoMessageLength = in.readInt();
			//byte[] intnum = new byte[4];
			//in.readBytes(intnum);
			System.out.println(_protoMessageLength);
		}
		
		while(_protoMessageLength != 0 && _protoMessageLength <= in.readableBytes()) {
			byte[] protoMessageBytes = new byte[_protoMessageLength];
			in.readBytes(protoMessageBytes);
			try {
				ProtoMessage message = ProtoMessage.parseFrom(protoMessageBytes);
				Request request = new Request();
				request._protoMessage = message;
				request._session = _session;
				_taskqueue.put(request);
			} catch (InvalidProtocolBufferException e) {
				Logger.Instance().logging(e.getMessage());
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			_protoMessageLength = 0;
		}
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) {
		System.out.println("[Client Disconnected to Server]"
				+ "{\nIOSession ID：" + _session.getID() + "\n}");
		Request request = new Request();
		SignoutRequest signal = SignoutRequest.newBuilder()
				.build();
		ProtoMessage protoMessage = ProtoMessage.newBuilder()
				.setSignoutRequest(signal)
				.build();
		request._session = _session;
		request._protoMessage = protoMessage;
		
		try {
			_taskqueue.put(request);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
}
